import * as vscode from "vscode";

import {
  GLOBAL_UI_SEARCH_EXTENSION_ID,
  GLOBAL_UI_SEARCH_TREE_VIEW_ID,
  GLOBAL_UI_SEARCH_WEB_VIEW_ID,
} from "../config";

export interface UiLibary {
  name: string;
  url: string;
  icon: TreeItem["iconPath"];
  children: UiLibary[];
}

// 自定义树项类
export class TreeItem extends vscode.TreeItem {
  readonly hasChildren: boolean;
  constructor(
    label: string,
    isExpandable: boolean = false,
    iconPath?: TreeItem["iconPath"]
  ) {
    super(label);
    this.iconPath = iconPath ?? "";
    this.hasChildren = isExpandable;
    this.collapsibleState = isExpandable
      ? vscode.TreeItemCollapsibleState.Collapsed
      : vscode.TreeItemCollapsibleState.None;
  }
}

export class SearchUiDoc {
  private readonly context: vscode.ExtensionContext;
  private readonly extensionId: string;
  private readonly webViewId: string;
  private readonly TreeViewId: string;
  private TreeView: vscode.TreeView<TreeItem> | null = null;
  private WebViewPanel: vscode.WebviewPanel | null = null;
  private nowSelectedItem: TreeItem | null = null;
  private uiLibaryList: UiLibary[] = [];

  constructor(context: vscode.ExtensionContext) {
    this.extensionId = GLOBAL_UI_SEARCH_EXTENSION_ID;
    this.webViewId = GLOBAL_UI_SEARCH_WEB_VIEW_ID;
    this.TreeViewId = GLOBAL_UI_SEARCH_TREE_VIEW_ID;
    this.context = context;
    this.uiLibaryList = this.getUiArr();
  }
  public initSearchUiDoc() {
    this.createTreeView();
    this.createWebViewPanel();
  }

  // 创建treeView 的命令
  private createTreeView() {
    const treeDataProvider: vscode.TreeDataProvider<TreeItem> = {
      getChildren: (element?: TreeItem): Thenable<TreeItem[]> => {
        if (element) {
          const index = this.uiLibaryList.findIndex(
            (item) => item.name === element.label
          );
          if (index < 0) {
            return Promise.resolve([]);
          }
          // 为展开的父节点提供子节点
          return Promise.resolve([
            ...this.uiLibaryList[index].children.map((child) => {
              return new TreeItem(child.name, false, child.icon);
            }),
          ]);
        } else {
          // 根节点没有父节点时提供子节点
          return Promise.resolve(
            this.uiLibaryList.map((item) => {
              return new TreeItem(item.name, !!item.children.length, item.icon);
            })
          );
        }
      },

      getTreeItem: (element: TreeItem): vscode.TreeItem => {
        return element;
      },

      // 支持展开和折叠
      getParent: (element: TreeItem): Thenable<TreeItem | null> => {
        return Promise.resolve(element ?? null); // 如果没有父节点，则返回 null
      },
    };

    // 注册 TreeView
    this.TreeView = vscode.window.createTreeView(this.TreeViewId, {
      treeDataProvider,
    });

    // 监听选中节点变化
    this.TreeView.onDidChangeSelection((e) => {
      if (e.selection.length > 0) {
        const selectedItem = e.selection[0];
        this.nowSelectedItem = selectedItem;
        if (!selectedItem.hasChildren) {
          this.openWbeViewPanel();
        }
      }
    });
  }

  /**
   * @description 描述 创建在编辑器中的web视图
   * @date 2024-11-29 15:55:08
   * @author tingfeng
   *
   * @private
   */
  private createWebViewPanel() {
    const { subscriptions } = this.context;
    // 注册命令
    subscriptions.push(
      vscode.commands.registerCommand(this.extensionId, () => {
        this.WebViewPanel = vscode.window.createWebviewPanel(
          this.webViewId,
          this.getTitleName(),
          vscode.ViewColumn.One,
          {
            enableScripts: true, // 启用 JavaScript
            // 如果你想加载外部资源, 可以添加这个配置
            retainContextWhenHidden: true,
            localResourceRoots: [], // 如果不需要加载本地资源，可以为空
          }
        );
        console.log(this.getWebviewContent());
        this.WebViewPanel.webview.html = this.getWebviewContent();
        this.WebViewPanel.iconPath = {
          light: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/UI-editor-light.svg")
          ),
          dark: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/UI-editor-dark.svg")
          ),
        };
      })
    );
  }

  /**
   * @description 描述 打开webview面板
   * @date 2024-11-29 15:54:53
   * @author tingfeng
   *
   * @private
   */
  private openWbeViewPanel() {
    vscode.commands.executeCommand(this.extensionId);
  }

  /**
   * @description 描述 获取ui库列表
   * @date 2024-11-29 15:54:47
   * @author tingfeng
   *
   * @private
   * @returns
   */
  private getTitleName() {
    let name = "";
    for (let index = 0; index < this.uiLibaryList.length; index++) {
      if (name === "") {
        const element = this.uiLibaryList[index];
        element.children.forEach((child) => {
          if (child.name === this.nowSelectedItem?.label) {
            name = child.name;
          }
        });
      }
    }
    return "UI文档 --" + name;
  }

  /**
   * @description 描述 获取webview内容
   * @date 2024-11-29 15:54:37
   * @author tingfeng
   *
   * @private
   * @returns
   */
  private getWebviewContent(): string {
    console.log(this.nowSelectedItem);
    let url = "";
    for (let index = 0; index < this.uiLibaryList.length; index++) {
      if (url === "") {
        const element = this.uiLibaryList[index];
        element.children.forEach((child) => {
          if (child.name === this.nowSelectedItem?.label) {
            url = child.url;
          }
        });
      }
    }

    if (url === "") {
      vscode.window.showInformationMessage("未找该文档");
      return "";
    }

    return `
      <!DOCTYPE html>
      <html lang="zh-CN">

      <head>
        <meta charset="UTF-8" />
        <meta name="referrer" content="no-referrer" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </head>

      <body style="height: 100vh;">
          <iframe src="${url}" width="100%" height="100%" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe>
      </body>

      </html>
    `;
  }

  /**
   * @description 描述 获取所有UI库
   * @date 2024-11-29 15:54:27
   * @author tingfeng
   *
   * @private
   * @returns
   */
  private getUiArr() {
    const uiLibaryList: UiLibary[] = [
      {
        name: "React",
        url: "https://react.docschina.org/learn",
        icon: {
          light: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/LogosReact.svg")
          ),
          dark: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/LogosReact.svg")
          ),
        },
        children: [
          {
            name: " Ant Design ",
            url: "https://ant-design.antgroup.com/docs/react/introduce-cn",
            icon: {
              light: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/LogosAntDesign.svg")
              ),
              dark: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/LogosAntDesign.svg")
              ),
            },
            children: [],
          },
          {
            name: " Arco Design React ",
            url: "https://arco.design/react/docs/start",
            icon: {
              light: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/Arco.svg")
              ),
              dark: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/Arco.svg")
              ),
            },
            children: [],
          },
        ],
      },
      {
        name: "Vue 2",
        url: "https://v2.cn.vuejs.org/",
        icon: {
          light: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/Vue2.svg")
          ),
          dark: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/Vue2.svg")
          ),
        },
        children: [
          {
            name: " Element Vue2",
            url: "https://element.eleme.cn/#/zh-CN",
            icon: {
              light: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/EpElementPlus.svg")
              ),
              dark: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/EpElementPlus.svg")
              ),
            },
            children: [],
          },
        ],
      },
      {
        name: "Vue 3",
        url: "https://cn.vuejs.org/guide/introduction",
        icon: {
          light: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/Vue3.svg")
          ),
          dark: vscode.Uri.file(
            this.context.asAbsolutePath("resources/dark/Vue3.svg")
          ),
        },
        children: [
          {
            name: " Ant Design Vue ",
            url: "https://www.antdv.com/components/",
            icon: {
              light: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/LogosAntDesign.svg")
              ),
              dark: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/LogosAntDesign.svg")
              ),
            },
            children: [],
          },
          {
            name: " Element Plus ",
            url: "https://element-plus.org/zh-CN/component/overview.html",
            icon: {
              light: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/EpElementPlus.svg")
              ),
              dark: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/EpElementPlus.svg")
              ),
            },
            children: [],
          },
          {
            name: " Arco Design Vue ",
            url: "https://arco.design/vue/docs/start",
            icon: {
              light: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/Arco.svg")
              ),
              dark: vscode.Uri.file(
                this.context.asAbsolutePath("resources/dark/Arco.svg")
              ),
            },
            children: [],
          },
        ],
      },
    ];

    return uiLibaryList;
  }
}
